package util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class ServerResponse {
    private HttpServletResponse resp;
    private Map<String, Object> data;

    public ServerResponse(HttpServletResponse resp) {
        this.resp = resp;
        this.resp.setContentType("text/html;charset=utf-8");
        data = new HashMap<>();
    }

    public void add(String name, Object o) {
        data.put(name, o);
    }

    /**
     * 提交数据，回应用户并清空数据
     * @return 成功返回true，失败返回false
     */
    public boolean commit() {
        PrintWriter p = null;
        try {
            p = resp.getWriter();
            p.write(JSONObject.toJSONString(data));

            data.clear();
            return true;
        } catch (IOException e) {
            return false;
        } finally {
            if(p != null) {
                p.flush();
                p.close();
            }
        }
    }
}
